# import jusmargui
from PySide2.QtWidgets import (
    QApplication,
    QWidget,
    QTableWidgetItem,
    QTableWidget,
    QHeaderView,
    QAbstractItemView,
    QVBoxLayout,
    QTabWidget,
    QGroupBox,
    QLabel,
    QLineEdit,
    QHBoxLayout,
    QGridLayout,
    QComboBox,
    QPushButton,
    QListWidget,
    QDialog,
    QButtonGroup,
    QRadioButton,
    QCheckBox,
    QListWidgetItem,
    QMessageBox,
    QGraphicsColorizeEffect,
    QFileDialog,
)
from PySide2.QtCore import Qt, Signal
from PySide2.QtGui import QPixmap, QDoubleValidator, QIntValidator, QImage
import sys
import csv
import os
import json
import subprocess
import copy
from .. import message_box as MBox
from .. import config as Config
from ..utils import Utils
from ..dlg_model_params import DlgModeResetCls
from ..params_table import ParamsTable, OnlyOneRowTable


class CGridLayout(QGridLayout):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setAlignment(Qt.AlignTop)


class DlgLumpedMass(DlgModeResetCls):
    lumpedMass_save_signal = Signal(object)

    def __init__(self, parent=None, params={}):
        super().__init__(parent)
        title = f"集中质量-{params.get('title')or''}"
        self.setWindowTitle(title)
        self.resize(650, 200)

        layout = QVBoxLayout()
        self.table = OnlyOneRowTable(rows=0, columns=8, isNoAddAndDel=True)
        # self.table.verticalHeader().setVisible(True)
        self.table.setHorizontalHeaderLabels(
            [
                "节点号",
                "x坐标",
                "y坐标",
                "z坐标",
                "质量",
                "x转动惯量",
                "y转动惯量",
                "z转动惯量",
            ]
        )
        self.table.rowSetInt([0])
        self.table.rowSetFloat([1, 2, 3, 4, 5, 6, 7])
        self.table.noEditHint = "该数据已入库，不可修改节点号！"
        self.table.uniqueFlagColumn = 0
        # self.table.setAddIncrementing(True)
        self.table.addRow()
        layout.addWidget(self.table)

        btnLayout = QHBoxLayout()
        # addBtn = QPushButton("新增")
        # importBtn = QPushButton("导入csv")
        clearBtn = QPushButton("清空")
        cancelBtn = QPushButton("取消")
        okBtn = QPushButton("确定")

        btnLayout.setAlignment(Qt.AlignCenter)
        # btnLayout.addWidget(addBtn)
        # btnLayout.addWidget(importBtn)
        btnLayout.addWidget(okBtn)
        btnLayout.addWidget(clearBtn)
        btnLayout.addWidget(cancelBtn)
        layout.addLayout(btnLayout)

        # addBtn.clicked.connect(self.on_addBtn_clicked)
        # importBtn.clicked.connect(self.on_importBtn_clicked)
        clearBtn.clicked.connect(self.on_clearBtn_clicked)
        okBtn.clicked.connect(self.on_okBtn_clicked)
        cancelBtn.clicked.connect(self.close)

        self.setLayout(layout)

        data = {}
        if Config.isLocation:
            self.cacheFile = Config.cachePath + "lumpedMass.json"
            data = Utils.read_json(self.cacheFile)
        else:
            data = params.get("data") or {}
        self.updateUI(data)
        Utils.handleTableNoEdit(data=data, table=self.table)

    def on_addBtn_clicked(self):
        self.table.addRow()

    # def on_importBtn_clicked(self):
    #     filePath = Utils.ImportFile()
    #     if filePath:
    #         _, fileExtension = os.path.splitext(filePath)
    #         fileExtension = fileExtension.lower()
    #         if fileExtension == ".json":
    #             self.loadTableList(filePath, self.table)
    #         elif fileExtension == ".csv":
    #             self.load_csv(filePath)

    def on_okBtn_clicked(self):
        dataList = self.table.getTableListFirstNoNull()
        data = {}
        if isinstance(dataList, int):
            MBox.warning(f"节点号不可为空!")
            return

        data["type"] = "point_mass"

        if dataList and len(dataList) > 0:
            item = [None if item == "" else item for item in dataList[0]]
            data["grid_id"] = item[0]
            data["cord"] = [item[1], item[2], item[3]]
            data["mass"] = item[4]
            data["inertia"] = [item[5], item[6], item[7]]

        data = Utils.filter_dict_list(data)
        filterDict = Utils.filterDictEmptyProperty(data)

        self.cacheFile = Config.cachePath + "lumpedMass.json"
        # data = Utils.sortDict(data)
        Utils.write_json(self.cacheFile, filterDict)
        self.close()
        self.lumpedMass_save_signal.emit(filterDict)

    def on_clearBtn_clicked(self):
        # self.table.clearRow()
        self.table.fillRowData(row=0, rowData=["", "", "", "", "", 0, 0, 0])

    def load_csv(self, filename):
        try:
            with open(
                filename, newline="", encoding="utf-8"
            ) as csvfile:  # 确保使用正确的编码
                reader = csv.reader(csvfile)
                csvData = list(reader)
                csvData = [row for row in csvData if row]
                oldNameList = self.get_first_column_values()
                # 如果第一行是对应的表头则删除
                del csvData[0]
                copyCsvData = csvData.copy()
                tableDict = self.table.getTableDict()
                for addIndex in range(len(copyCsvData) - 1, -1, -1):  # 倒序遍历
                    csvRow = copyCsvData[addIndex]
                    if csvRow[0] is not None and str(csvRow[0]) in tableDict:
                        self.table.updateRowData(
                            tableDict[str(csvRow[0])]["row"], csvRow
                        )
                        del csvData[addIndex]
                self.table.addMulitRows(csvData)
        except FileNotFoundError:
            print(f"Error: 文件 '{filename}' 未找到.")

    def get_first_column_values(self):
        # 获取第一列的所有值
        first_column_values = []
        for i in range(self.table.rowCount()):
            item = self.table.item(i, 0)  # 获取第0列的单元格
            if item is not None:
                first_column_values.append(item.text().strip())
            else:
                first_column_values.append("")  # 如果单元格为空，则添加空字符串
        return first_column_values

    def updateUI(self, data):
        if data:
            cord = Utils.process_array(data.get("cord") or [], 3)
            inertia = Utils.process_array(data.get("inertia") or [], 3)
            dataList = (
                ([data.get("grid_id")] or [])
                + cord
                + ([data.get("mass")] or [])
                + inertia
            )
            all_non_empty = all(item == "" or item is None for item in dataList)
            if not all_non_empty:
                self.table.fillRowData(row=0, rowData=dataList)
        else:
            self.table.fillRowData(row=0, rowData=["", "", "", "", "", 0, 0, 0])

    # def loadTableList(self, file, table):
    #     data = Utils.read_json(file)
    #     for row_data in data:
    #         table.addRow(rowData=row_data)


# if __name__ == "__main__":
#     app = QApplication(sys.argv)
#     window = LumpedMassDialog()
#     window.show()
#     sys.exit(app.exec_())
